#!/bin/bash

REGISTER_LOG_FILE=/var/log/register-device-curl.log
PIN_LOG_FILE=/var/log/pinning-device-curl.log

PINNING_CONF=/etc/resin-device-pinning.conf

help () {
    cat << EOF
Register a new resin device
resin-device-register [options]

Options:
    -h, --help
        Display this help and exit.

    -c, --config-path CONFIG_PATH
        Use a non default config.json file.
        This argument is passed to balena-config-vars script.
EOF
}

# Parse arguments
while [ $# -gt 0 ]; do
    key=$1
    case $key in
        -h|--help)
            help
            exit 0
            ;;
        -c|--config-path)
            BALENA_VARS_ARGS="$BALENA_VARS_ARGS --config-path $2"
            shift
            ;;
        *)
            echo "[WARNING] $0 : Argument '$1' unknown. Ignoring."
            ;;
    esac
    shift
done

# shellcheck disable=SC2086
source /usr/sbin/balena-config-vars $BALENA_VARS_ARGS
source /etc/balena-supervisor/supervisor.conf

if [ -z "$API_ENDPOINT" ] || [ -z "$CONFIG_PATH" ]; then
    echo "[ERROR] resin-device-register : Please set API_ENDPOINT and CONFIG_PATH environment variables."
    exit 1
fi

while true; do
    if curl -sL -w '%{http_code}' "$API_ENDPOINT"/ping -o /dev/null | egrep "20[0-9]|30[0-9]" >/dev/null
    then
        if [ -n "${REGISTERED_AT}" ]; then
            echo "[INFO] resin-device-register : Device already registered."
        else
            status_code=$(curl -s -X POST -w "%{http_code}" \
                        --header "Authorization: Bearer $PROVISIONING_API_KEY" \
                        --output $REGISTER_LOG_FILE \
                        --data-urlencode "application=$APPLICATION_ID" \
                        --data-urlencode "device_type=$DEVICE_TYPE" \
                        --data-urlencode "uuid=$UUID" \
                        --data-urlencode "api_key=$DEVICE_API_KEY" \
                        ${SUPERVISOR_VERSION:+ --data-urlencode "supervisor_version=${SUPERVISOR_VERSION}"} \
                        "$API_ENDPOINT/device/register")

            if [ "$status_code" -eq 201 ]; then
                device_id=$(jq -r '.id' $REGISTER_LOG_FILE)
                "${CAT}" "${CONFIG_PATH}" | jq -S ".registered_at=\"$(date +%s)\"|.deviceId=\"$device_id\"|del(.apiKey)" | "${WR}" "${CONFIG_PATH}"
                echo "[INFO] resin-device-register : Registered device with ID: $device_id and UUID: $UUID."
                # Regenerate the VPN credentials to stop using `apiKey`
                systemctl restart prepare-openvpn
            else
                echo "[ERROR] resin-device-register : Failed to register device. Status code: $status_code"
            fi

        fi

        if [ -f ${PINNING_CONF} ]; then
            source "${PINNING_CONF}"

            status_code=$(curl -s -X PATCH -w "%{http_code}" \
                --header "Authorization: Bearer $DEVICE_API_KEY" \
                --output $PIN_LOG_FILE \
                --data-urlencode "should_be_running__release=$RELEASE_ID" \
                "$API_ENDPOINT/v6/device(uuid='${UUID}')")

            if [ "$status_code" -eq 200 ]; then
                echo "[INFO] resin-device-pinning: Pinned device ${UUID} to release ${RELEASE_ID}"
                exit 0
            else
                echo "[ERROR] resin-device-pinning : Failed to pin device release. Status code: $status_code"
                exit 0
            fi
        else
            echo "[INFO] resin-device-pinning : Pinning information missing. Skipping."
            exit 0
        fi
    else
        echo  "[WARNING] resin-device-register: Not connected. Trying again..."
        sleep 2
    fi
done
